var map
	var infoWin = null
	var point_mark = new Array()
	var polygon_arr = new Array()
	var log_load_flag = 0
	$(function(){
	 	showMap()
	 	companyList()
	 	btnSearch()
	 	togglePane()
	 	staticClick()
	})
	function showMap() {
		// 百度地图API功能
		map = new BMap.Map('allmap', { mapType: BMAP_NORMAL_MAP }) // 创建Map实例
		map.centerAndZoom(new BMap.Point(120.523039,36.193397), 15) // 初始化地图,设置中心点坐标和地图级别
		//添加地图类型控件
		map.addControl(new BMap.MapTypeControl({
			mapTypes:[
	            BMAP_NORMAL_MAP,
	            BMAP_SATELLITE_MAP,
	            BMAP_HYBRID_MAP
	        ]
	}))	  
		map.setCurrentCity('青岛') // 设置地图显示的城市 此项是必须设置的
		map.enableScrollWheelZoom(true) //开启鼠标滚轮缩放
		
		var hei = $('.BMap_mask').height()
		// $(".iushe").css("height",hei-500+"px");
	}
	
	/*添加右侧面般*/
	function companyList()
	{
		var comName = $('#company').val()
		var select_category = $('input[name=\'category\']:checked')
		var category_len = select_category.length
		var category_str = ''
		var category_arr = []
		for(var i=0;i<category_len;i++) {
			category_arr.push(select_category[i].value)
		}
		category_str = category_arr.join(',')
		$.messager.progress({
	        title: '温馨提示',
	        msg: '系统正在努力加载数据',
	        interval: 500
	    })
		$.ajax({ 
			url: '/admin/getAllCompany3', 
			dataType: 'json',
			data:{ name:comName,category:category_str },
			type: 'get',
			success: function(data){
				$.messager.progress('close')
				var com=data.comarr
				map.clearOverlays()
				clearSelectClass()
				
				point_mark = []
				polygon_arr = []
				loadPolygon()
					
				addPoint(com)
				
				var list=data.dataarr
				var html = []
				var len = list.length
				$('#companyList').html('')
				html.push('<tr style="height: 20px;width: 100%;cursor:pointer">')
				html.push('<td style="text-align: left;width:10%">序  号</td>')
				html.push('<td id="qy_0" style="text-align: left;width:30%">物资名称</td>')
				html.push('<td id="qy_0" style="text-align: left;width:30%">分类名称</td>')
				html.push('<td id="qy_0" style="text-align: left;width:15%">库存数量</td>')
				html.push('<td style="text-align: center;width:15%">操  作</td>')
				html.push('</tr>')
				for(var i= 0;i<len; i++) {
					html.push('<tr style="height: 20px;width: 100%;cursor:pointer">')
					html.push('<td style="text-align: left;width:10%">'+(i + 1)+'</td>')
					html.push('<td id="qy_0" style="text-align: left;width:30%" onmouseover="this.style.backgroundColor=\'#ffff66\';" onmouseout="this.style.backgroundColor=\'#d4e3e5\';">'+ list[i].name +'</td>')
					html.push('<td id="qy_0" style="text-align: left;width:30%" onmouseover="this.style.backgroundColor=\'#ffff66\';" onmouseout="this.style.backgroundColor=\'#d4e3e5\';">'+ list[i].goods.name +'</td>')
					html.push('<td id="qy_0" style="text-align: left;width:15%" onmouseover="this.style.backgroundColor=\'#ffff66\';" onmouseout="this.style.backgroundColor=\'#d4e3e5\';">'+ list[i].warehouse +'</td>')
					html.push('<td onmouseover="this.style.backgroundColor=\'#ffff66\';" onmouseout="this.style.backgroundColor=\'#d4e3e5\';" style="text-align: center;width:15%" onclick="openInfostock('+list[i].id+')">详情</td>')
					html.push('</tr>')
				}
				$('#companyList').append(html.join(''))
				
				
				
				
				
				
		    },
		    error: function(){
		    	$.messager.progress('close')
		    	$.messager.alert('系统提示', '出错了,请重新加载', 'info')
		    }
	    })
	}
	function openInfostock(id) {
		var url = '/admin/warehouse/materialdetail?id='+id
		window.location.href=url
	}
	function openInfo(id) {
		var url = '/admin/stock/list?company_id='+id
		window.location.href=url
	}
	function addPoint(data)
	{
		/*添加点*/
		var len = data.length
		for(var i=0;i<len;i++) {
			var point = new BMap.Point(data[i]['lng'], data[i]['lat'])       
			var marker = new BMap.Marker(point, { icon: getIcon(data[i].has_danger,data[i].enterprise) }) // 创建标注    
			map.addOverlay(marker)
			marker.companyId = data[i].id
			point_mark.push(marker)
		}
		pointEnvent(point_mark)
	}
	/*点添加点击事件*/
	function pointEnvent(point_mark)
	{
		var len = point_mark.length
		var current_pint_mark = new Array()
		for(var i=0;i<len;i++) {
			(function () {
	            var current_pint_mark = point_mark[i]
	            current_pint_mark.addEventListener('click', function () {
	                clickPoint(current_pint_mark)
	            })
	        })()
		}
	}
	/*点击点的时候获取公司信息*/
	function clickPoint(point_mark)
	{
		/*获取公司信息*/
		$.ajax({ 
			url: '/admin/getCompany', 
			dataType: 'json',
			data:'id='+point_mark.companyId,
			type: 'get',
			success: function(data){
				var html = []
				html.push('<div width="100%" margin="5px 5px 5px 5px">')
				html.push(' <table cellspacing="0" cellspadding="0" style="width:auto">')
				html.push('     <tr>')
	            html.push('         <td style="text-align:left;">单位名称：</td>')
	            html.push('         <td><label>' + data.comName + '</label></td>')
	            html.push('     </tr>')
	            html.push('     <tr>')
	            html.push('         <td style="text-align:left;width:110px;">单位负责人及联系方式：</td>')
	            html.push('         <td><label>' + data.leader + ' ' + data.leaderPhone + '</label></td>')
	            html.push('     </tr>')
	            html.push('     <tr>')
	            html.push('         <td style="text-align:left">单位地址：</td>')
	            html.push('         <td><label>' + data.address + '</label></td>')
	            html.push('     </tr>')
	            html.push('     <tr>')
	            html.push('         <td style="text-align:left">单位人数：</td>')
	            html.push('         <td><label>' + data.workersNum + '</label></td>')
	            html.push('     </tr>')
	            html.push('     <tr>')
	            html.push('         <td style="text-align:left">单位占地面积：</td>')
	            html.push('         <td><label>' + data.space + '</label></td>')
	            html.push('     </tr>')
	            html.push('     <tr>')
	            html.push('         <td style="text-align:left;"><a style="color: #2ea7e0;font-size: 18px;" onclick="openInfo('+data.id+')" href="javascript:;">查看仓库详情</a></td>')
	            html.push('     </tr>')
				html.push(' </table>')
				html.push('</div>')
				var opts = {
	                    width: 0, // 信息窗口宽度
	                    height: 0, // 信息窗口高度
	                    title: '企业信息', // 信息窗口标题
	                    enableMessage: true,//设置允许信息窗发送短息
	                    message: ''
	                }
	             infoWin = new BMap.InfoWindow(html.join(''), opts) // 创建信息窗口对象
	             map.openInfoWindow(infoWin, point_mark.point) //开启信息窗口
		    },
		    error: function(){
		    	$.messager.alert('系统提示', '出错了,请重新加载', 'info')
		    }
	    })
	}
	/*点击企业定位*/
	function findPoint(companyId, i) {
	    var lnglat = point_mark[i].point
	    if (lnglat.lat != 0 && lnglat.lng != 0) {
	        map.centerAndZoom(lnglat, 15)
	        point_mark[i].companyId = companyId
	        map.removeOverlay(infoWin)
	        clickPoint(point_mark[i])
	    }
	    else {
	    	$.messager.alert('系统提示', '该企业尚未确认坐标信息', 'info')
	    }
	}
	function getIcon(flag,enterprise=1) {
	    var iconurl = ''
		iconurl = '/images/admin/map/com_green.png'
		// if(enterprise==1){
		// 	// 企业
		// 	if (flag == 1) {
		// 		// 一般隐患
		// 	    iconurl = '/images/admin/map/com_red.gif'
		// 	}else if(flag == 2) {
		// 		// 重大隐患
		// 		iconurl = '/images/admin/map/com_black.gif'
		// 	}else {
		// 		// 无隐患
		// 	    iconurl = '/images/admin/map/com_green.png'
		// 	}
		// }else if(enterprise==2){
		// 	// 九小场所
		// 	if (flag == 1) {
		// 	    iconurl = '/images/admin/map/nine_red.gif'
		// 	}else if(flag == 2) {
		// 		iconurl = '/images/admin/map/nine_black.gif'
		// 	}else {
		// 	    iconurl = '/images/admin/map/nine_green.png'
		// 	}
		// }else{
		// 	// 住户
		// 	if (flag == 1) {
		// 	    iconurl = '/images/admin/map/resident_red.gif'
		// 	}else if(flag == 2) {
		// 		iconurl = '/images/admin/map/resident_black.gif'
		// 	}else {
		// 	    iconurl = '/images/admin/map/resident_green.png'
		// 	}
		// }
	    var icon = new BMap.Icon(iconurl, new BMap.Size(20, 20))
		icon.setImageSize(new BMap.Size(20,20))//设置图标大小
	    if (iconurl == '/images/admin/map/com_green.png') {
	        icon = new BMap.Icon(iconurl, new BMap.Size(16, 16))
			icon.setImageSize(new BMap.Size(16,16))//设置图标大小
	    }
	    return icon
	}
	function btnSearch()
	{
		$('#btnSearch').click(function(){
			companyList()
		})
	}
	function togglePane()
	{
		$('#qytz').click(function() {
			$('.diyi-s').show()
			$('.dier-s').hide()
			$('#hues').show()
			$('#qytz').addClass('chcerss')
			$('#jcjl').removeClass('chcerss')
			$('.iushe').css('height','400px')
		})
		$('#jcjl').click(function() {
			if(log_load_flag==0) {
				loadLogData()
				logBtnSearch()
			}
			$('#hues').hide()
			$('.diyi-s').hide()
			$('.dier-s').show()
			$('#jcjl').addClass('chcerss')
			$('#qytz').removeClass('chcerss')
			$('.iushe').css('height','572px')
			
		})
	}
	/*加载检查记录数据*/
	function loadLogData()
	{
		var comName = $('#log_company').val()
		$.messager.progress({
	        title: '温馨提示',
	        msg: '系统正在努力加载数据',
	        interval: 500
	    })
		$.ajax({ 
			url: '/admin/getCheckLogs', 
			dataType: 'json',
			data:{ name:comName },
			type: 'get',
			success: function(data){
				$.messager.progress('close')
				var html = []
				var len = data.length
				$('#checkLog').html('')
				for(var i= 0;i<len; i++) {
					html.push('<tr style="height: 20px;width: 100%;cursor:pointer">')
					html.push('<td style="text-align: left;width:10%">'+(i + 1)+'</td>')
					html.push('<td id="qy_0" style="text-align: left;width:65%" onclick="openInfo('+data[i].id+')" onmouseover="this.style.backgroundColor=\'#ffff66\';" onmouseout="this.style.backgroundColor=\'#d4e3e5\';">'+ data[i].comName +'</td>')
					html.push('<td onmouseover="this.style.backgroundColor=\'#ffff66\';" onclick="openInfo('+data[i].id+')" onmouseout="this.style.backgroundColor=\'#d4e3e5\';" style="text-align: left;width:25%">'+data[i].checkTime+'</td>')
					html.push('</tr>')
					
				}
				$('#checkLog').append(html.join(''))
				log_load_flag = 1
		    },
		    error: function(){
		    	$.messager.progress('close')
		    	$.messager.alert('系统提示', '出错了,请重新加载', 'info')
		    }
	    })
	}
	/*检查记录搜索*/
	function logBtnSearch()
	{
		$('#logBtnSearch').click(function(){
			loadLogData()
		})
	}
	/*获取圆的中心*/
	function getCenter(type,point_arr)
	{
	    var Max = 0
	    var Min = 0
	    if (point_arr.length > 0) {
	        for (var i = 0; i < point_arr.length; i++) {
	            var xxyy = point_arr[i].split(',')
	            if (i == 0) {
	                if (type == 'x') {
	                    Max = xxyy[0]
	                    Min = xxyy[0]
	                }
	                else {
	                    Max = xxyy[1]
	                    Min = xxyy[1]
	                }
	            }
	            else {
	                if (type == 'x') {
	                    if (Min > xxyy[0]) {
	                        Min = xxyy[0]
	                    }
	                    if (Max < xxyy[0]) {
	                        Max = xxyy[0]
	                    }
	                }
	                else {
	                    if (Min > xxyy[1]) {
	                        Min = xxyy[1]
	                    }
	                    if (Max < xxyy[1]) {
	                        Max = xxyy[1]
	                    }
	                }
	            }
	        }
	        return (Number(Min) + Number(Max)) / 2
	    }
	    else {
	        return 0
	    }
	}
	function loadPolygon()
	{
		$.ajax({ 
			url: '/admin/getCommunity', 
			dataType: 'json',
			data:{},
			type: 'get',
			success: function(data){
				var len = data.length
				for(var i= 0;i<len; i++) {
					var lng_lat_str = data[i].lng_lat
					var lng_lat_arr = lng_lat_str.split('|')
					var lng_lat_len = lng_lat_arr.length
					var points = []
					for(var j=0;j<lng_lat_len;j++) {
						var lng_lat = lng_lat_arr[j].split(',')
						points.push(new BMap.Point(lng_lat[0],lng_lat[1]))
					}
					var color = data[i].color
					polygon_arr[i] = new BMap.Polygon(points, { strokeColor: color, strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: color })
					map.addOverlay(polygon_arr[i])
					polygon_arr[i].area_name = data[i].name
					polygon_arr[i].lng_lat = data[i].lng_lat
				}
				polygonEvent(polygon_arr)
		    },
		    error: function(){
		    	$.messager.alert('系统提示', '出错了,请重新加载', 'info')
		    }
	    })
	}
	/*社区事件*/
	function polygonEvent(polygon_arr)
	{
		var len= polygon_arr.length
		for(var i=0;i<len;i++) {
			(function () {
				var current_polygon = polygon_arr[i]
				current_polygon.addEventListener('click',function(e){
	            	clickPolygon(current_polygon)
				})
			})()
		}
	}
	/*社区点击事件*/
	function clickPolygon(polygon)
	{
		var lng_lat_str = polygon.lng_lat
		var lng_lat_arr = lng_lat_str.split('|')
		var xxc = getCenter('x',lng_lat_arr)
		var yyc = getCenter('y',lng_lat_arr)
		var point = new BMap.Point(xxc,yyc)
		var opts = {
	                width: 0, // 信息窗口宽度
	                height: 0 // 信息窗口高度
	                //title: "", // 信息窗口标题
	                //enableMessage: true,//设置允许信息窗发送短息
	                //message: ""
	            }
		var info = new BMap.InfoWindow(polygon.area_name, opts)
		map.openInfoWindow(info, point)
	}
	function staticClick()
	{
		$('#superviseCompany').click(function(){
			$('#companyCheck').removeClass('show')
			$('#danger').removeClass('show')
			if($(this).hasClass('show')) {
				companyList()
				$(this).removeClass('show')
				$(this).parents('li.ertd').removeClass('chcer')
				
			} else {
				map.clearOverlays()
				loadSuperviseCompany()
				$(this).addClass('show')
				
	//			$(this).addClass("chcerss")
				$(this).parents('li.ertd').addClass('chcer')
				$(this).parents('li.ertd').siblings().removeClass('chcer')
				
			}
		})
		$('#companyCheck').click(function(){
			$('#superviseCompany').removeClass('show')
			$('#danger').removeClass('show')
			if($(this).hasClass('show')) {
				companyList()
				$(this).removeClass('show')
				
				$(this).parents('li.ertd').removeClass('chcer')
			} else {
				map.clearOverlays()
				loadCompanyCheck()
				$(this).addClass('show')
				$(this).parents('li.ertd').addClass('chcer')
				$(this).parents('li.ertd').siblings().removeClass('chcer')
			}
			
		})
		$('#danger').click(function(){
			$('#superviseCompany').removeClass('show')
			$('#companyCheck').removeClass('show')
			if($(this).hasClass('show')) {
				companyList()
				$(this).removeClass('show')
				
				$(this).parents('li.ertd').removeClass('chcer')
			} else {
				map.clearOverlays()
				loadDangersData()
				$(this).addClass('show')
				$(this).parents('li.ertd').addClass('chcer')
				$(this).parents('li.ertd').siblings().removeClass('chcer')
			}
			
		})
	}
	function loadCompanyCheck()
	{
		$.ajax({ 
			url: '/admin/getCompanyNum', 
			dataType: 'json',
			data:{},
			type: 'get',
			success: function(data){
				var len = data.length
				var circles = []
				polygon_arr = []
				for(var i= 0;i<len; i++) {
					var lng_lat_str = data[i].lng_lat
					var lng_lat_arr = lng_lat_str.split('|')
					var lng_lat_len = lng_lat_arr.length
					var points = []
					for(var j=0;j<lng_lat_len;j++) {
						var lng_lat = lng_lat_arr[j].split(',')
						points.push(new BMap.Point(lng_lat[0],lng_lat[1]))
					}
					var color = data[i].color
					polygon_arr[i] = new BMap.Polygon(points, { strokeColor: color, strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: color })
					map.addOverlay(polygon_arr[i])
					polygon_arr[i].area_name = data[i].name
					polygon_arr[i].lng_lat = data[i].lng_lat
					/*画圆*/
					var xxc = getCenter('x', lng_lat_arr)
					var yyc = getCenter('y', lng_lat_arr)
					var center_point = new BMap.Point(xxc,yyc)
					circles[i] = new BMap.Circle(center_point, 240,{ strokeColor: 'green', strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: 'green' })
					var opts = {
						position:center_point,
						offset:new BMap.Size(-20,-20)
					}
					var label = new BMap.Label(data[i].name+'<br/>'+data[i].num+'家企业', opts)
					label.setStyle({
						color: '#FFF',
	                    backgroundColor: 'transparent',//文本背景色
	                    borderColor: 'transparent',//文本框边框色
	                    fontSize: '11px',
	                    fontFamily: '微软雅黑',
	                    textAlign: 'center'
					})
					map.addOverlay(circles[i])
					map.addOverlay(label)
	
				}
				polygonEvent(polygon_arr)
				circleEvent(circles)
		    },
		    error: function(){
		    	$.messager.alert('系统提示', '出错了,请重新加载', 'info')
		    }
	    })
	}
	function circleEvent(circles)
	{
		var len = circles.length
		for(var i=0;i<len;i++) {
			(function(){
				var current_circle = circles[i]
				current_circle.addEventListener('mouseout', function(){
					current_circle.setFillColor('green')
				})
				current_circle.addEventListener('mouseover', function(){
					current_circle.setFillColor('orange')
				})
			})()
		}
	}
	function loadDangersData()
	{
		$.ajax({ 
			url: '/admin/getDangersNum', 
			dataType: 'json',
			data:{},
			type: 'get',
			success: function(data){
				var len = data.length
				var circles = []
				polygon_arr = []
				for(var i= 0;i<len; i++) {
					var lng_lat_str = data[i].lng_lat
					var lng_lat_arr = lng_lat_str.split('|')
					var lng_lat_len = lng_lat_arr.length
					var points = []
					for(var j=0;j<lng_lat_len;j++) {
						var lng_lat = lng_lat_arr[j].split(',')
						points.push(new BMap.Point(lng_lat[0],lng_lat[1]))
					}
					var color = data[i].color
					polygon_arr[i] = new BMap.Polygon(points, { strokeColor: color, strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: color })
					map.addOverlay(polygon_arr[i])
					polygon_arr[i].area_name = data[i].name
					polygon_arr[i].lng_lat = data[i].lng_lat
					/*画圆*/
					var xxc = getCenter('x', lng_lat_arr)
					var yyc = getCenter('y', lng_lat_arr)
					var center_point = new BMap.Point(xxc,yyc)
					circles[i] = new BMap.Circle(center_point, 240,{ strokeColor: 'green', strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: 'green' })
					var opts = {
						position:center_point,
						offset:new BMap.Size(-20,-20)
					}
					var label = new BMap.Label(data[i].name+'<br/>'+data[i].danger_num+'条隐患', opts)
					label.setStyle({
						color: '#FFF',
	                    backgroundColor: 'transparent',//文本背景色
	                    borderColor: 'transparent',//文本框边框色
	                    fontSize: '11px',
	                    fontFamily: '微软雅黑',
	                    textAlign: 'center'
					})
					map.addOverlay(circles[i])
					map.addOverlay(label)
	
				}
				polygonEvent(polygon_arr)
				circleEvent(circles)
		    },
		    error: function(){
		    	$.messager.alert('系统提示', '出错了,请重新加载', 'info')
		    }
	    })
	}
	function loadSuperviseCompany()
	{
		$.ajax({ 
			url: '/admin/getSuperviseCompanyNum', 
			dataType: 'json',
			data:{},
			type: 'get',
			success: function(data){
				var len = data.length
				var circles = []
				polygon_arr = []
				for(var i= 0;i<len; i++) {
					var lng_lat_str = data[i].lng_lat
					var lng_lat_arr = lng_lat_str.split('|')
					var lng_lat_len = lng_lat_arr.length
					var points = []
					for(var j=0;j<lng_lat_len;j++) {
						var lng_lat = lng_lat_arr[j].split(',')
						points.push(new BMap.Point(lng_lat[0],lng_lat[1]))
					}
					var color = data[i].color
					polygon_arr[i] = new BMap.Polygon(points, { strokeColor: color, strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: color })
					map.addOverlay(polygon_arr[i])
					polygon_arr[i].area_name = data[i].name
					polygon_arr[i].lng_lat = data[i].lng_lat
					/*画圆*/
					var xxc = getCenter('x', lng_lat_arr)
					var yyc = getCenter('y', lng_lat_arr)
					var center_point = new BMap.Point(xxc,yyc)
					circles[i] = new BMap.Circle(center_point, 240,{ strokeColor: 'green', strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: 'green' })
					var opts = {
						position:center_point,
						offset:new BMap.Size(-20,-20)
					}
					var num = 0
					if(data[i].num!=null) {
						num = data[i].num
					}
					var label = new BMap.Label(data[i].name+'<br/>'+num+'家企业', opts)
					label.setStyle({
						color: '#FFF',
	                    backgroundColor: 'transparent',//文本背景色
	                    borderColor: 'transparent',//文本框边框色
	                    fontSize: '11px',
	                    fontFamily: '微软雅黑',
	                    textAlign: 'center'
					})
					map.addOverlay(circles[i])
					map.addOverlay(label)
				}
				polygonEvent(polygon_arr)
				circleEvent(circles)
		    },
		    error: function(){
		    	$.messager.alert('系统提示', '出错了,请重新加载', 'info')
		    }
	    })
	}
	function clearSelectClass()
	{
		$('.ertd').removeClass('chcer')
	}